/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2019 Code Technology Studio
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package org.dromara.jpom.socket.handler;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONValidator;
import lombok.extern.slf4j.Slf4j;
import org.dromara.jpom.common.forward.NodeUrl;
import org.dromara.jpom.model.data.NodeModel;
import org.dromara.jpom.model.user.UserModel;
import org.dromara.jpom.permission.ClassFeature;
import org.dromara.jpom.permission.Feature;
import org.dromara.jpom.permission.MethodFeature;
import org.dromara.jpom.socket.BaseProxyHandler;
import org.dromara.jpom.socket.ConsoleCommandOp;
import org.dromara.jpom.transport.IProxyWebSocket;
import org.dromara.jpom.util.SocketSessionUtil;
import org.dromara.jpom.util.StringUtil;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * 脚本模板消息控制器
 *
 * @author bwcx_jzy
 * @since 2019/4/24
 */
@Feature(cls = ClassFeature.SSH_TERMINAL, method = MethodFeature.EXECUTE)
@Slf4j
public class WebSSHHandler extends BaseProxyHandler {
    public WebSSHHandler() {
        super(NodeUrl.WebSSH);
    }

    @Override
    protected Object[] getParameters(Map<String, Object> attributes) {
        UserModel userModel = (UserModel)attributes.get("userInfo");

        return new Object[]{"user_uuid", userModel.getId()+"_"+ IdUtil.fastSimpleUUID()};
    }

    @Override
    public void afterConnectionEstablishedImpl(WebSocketSession session) throws Exception{
        super.afterConnectionEstablishedImpl(session);
        //ws 建立后开始发送命令让agent建立ssh连接
        IProxyWebSocket proxySession = (IProxyWebSocket)session.getAttributes().get("proxySession");
        Map connectMap = new HashMap();
        connectMap.put("operate", "connect");
        proxySession.send(JSONObject.toJSONString(connectMap));

    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //发起ws client 连到 agent中的ws server
        //将用户输入转发到 agent ws server
        //将 agent ws server的输出转发到用户
        log.info(message.getPayload());
        IProxyWebSocket proxySession = (IProxyWebSocket)session.getAttributes().get("proxySession");

        if(proxySession!=null && proxySession.isConnected()){
            Map commandMap = new HashMap();
            commandMap.put("operate", "command");
            commandMap.put("command", message.getPayload());

            proxySession.send(JSONObject.toJSONString(commandMap));
        }
    }
    @Override
    public void destroy(WebSocketSession session) {
        super.destroy(session);
        log.info("来之用户侧的ws已关闭");
    }
}
